/***********************************************************************************
  *FileName:  timer.c
  *Version:   V1.0
  *Date:      2024-10-17
****************************************Includes************************************/
#include "timer.h"
#include "misc.h"
#include "nsuc16xx_conf.h"

/***************************************Variables***********************************/
TMR0_Struct_t TMRO_Status;
/***************************************Functions***********************************/
/**
 * @brief  禁止更新位
 * @param None
 * @retval None
 */
void TIM_UDIS(TIMER_TypeDef *TMRx, uint8_t Type)
{
  (Type != DISABLE)?(TMRx->CR_b.UDIS = 0):(TMRx->CR_b.UDIS = 1);
}


/**
 * @brief  定时器初始化
 * @param None
 * @retval None
 */
void Timer0Init(void)
{
  RCC_APBPeriphClockCmd(RCC_APBPeriph_TIM0,ENABLE);       /* 使能 APB 定时器 TIM0 时钟 */

  LL_NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_1);      /* 设置1位抢占，2位响应优先级 */
  LL_NVIC_EnableIRQ(TMR0_IRQn);                           /* 使能定时器0中断 */
  LL_NVIC_SetPriority(TMR0_IRQn, 0, 3);                   /* 配置定时器中断 0抢占优先级,3响应优先级 */

  TMR_TimeBaseInitTypeDef TMR_TimeBaseInitStruct;         /* 定时器权柄 */
  TMR_TimeBaseInitStruct.TMR_Prescaler = 31999;             /* 预分频器系数 T = 32M/(31999 + 1) = 1000*/
  TMR_TimeBaseInitStruct.TMR_UpdateInterrupt = DISABLE;    /* 定时器更新中断 */
  TMR_TimeBaseInitStruct.TMR_FinishedInterrupt = ENABLE;  			/* 定时器完成中断 */ 
  TMR_TimeBaseInitStruct.TMR_AutoReload = DISABLE;         /* 定时器自动重装载 */
  TMR_TimeBaseInitStruct.TMR_StartCounter = 0;            /* 定时器开始计数值 */
  TMR_TimeBaseInitStruct.TMR_EndCounter = 999;          /* 装载值 1000/T = 1000 / 1000 = 1S*/

  TMR_TimeBaseInit(TMR0,&TMR_TimeBaseInitStruct);         /* 初始化定时器配置 */
  TIM_UDIS(TMR0,DISABLE);                                 /* 禁用UEV更新事件 */
} 

uint8_t num[2] = {0};
uint8_t CurrentCount = 0;
/**
 * @brief 定时器0中断回调函数 
 * @param None
 * @retval None
 */
void TMR0Handler(void)
{
	TMRO_Status.TMR0_IT_OV = TMR_GetITStatus(TMR0,TMR_IT_OV);
	TMRO_Status.TMR0_IT_Update = TMR_GetITStatus(TMR0,TMR_IT_Update);
	CurrentCount = TMR_GetCounter(TMR0);
  static int status = 0;
	static int flag = 0;
  if(TMR_GetITStatus(TMR0,TMR_IT_Update) == SET)
  {
    if(status == 1)
    {
      GPIO_SetBits(GPIO_Pin_3);
			status = 0;
    }
    else
    {
      GPIO_ResetBits(GPIO_Pin_3);
			status = 1;
    } 
    TMR_ClearITPendingBit(TMR0,TMR_IT_Update);
		num[0]++;
  }
  if(TMR_GetITStatus(TMR0,TMR_IT_OV) == SET)
  {
    if(flag == 1)
    {
      GPIO_SetBits(GPIO_Pin_4);
			flag = 0;
    }
    else
    {
      GPIO_ResetBits(GPIO_Pin_4);
			flag = 1;
    }
    TMR_ClearITPendingBit(TMR0,TMR_IT_OV);
		num[1]++;
  }
}

/***************************************END OF FILE*********************************/
